import { Controller, Get, Post, Put, Delete, Body, Param, Query, UseGuards } from '@nestjs/common';
import { WorkflowService } from '../services/workflow.service';
import { WorkflowTemplate } from '../interfaces/workflow.interface';
import { JwtAuthGuard } from '../../auth/guards/jwt-auth.guard';
import { RolesGuard } from '../../auth/guards/roles.guard';
import { Roles } from '../../auth/decorators/roles.decorator';
import { ApiTags, ApiOperation, ApiResponse, ApiQuery } from '@nestjs/swagger';
import { SortOrder } from 'mongoose';
import { Logger } from '@nestjs/common';

@ApiTags('templates')
@Controller('api/templates')
export class WorkflowController {
    private readonly logger = new Logger(WorkflowController.name);

    constructor(private workflowService: WorkflowService) { }

    @Get()
    @ApiOperation({ summary: '获取模板列表' })
    @ApiResponse({ status: 200, description: '成功获取模板列表' })
    @ApiQuery({ name: 'page', required: false, type: Number })
    @ApiQuery({ name: 'pageSize', required: false, type: Number })
    @ApiQuery({ name: 'category', required: false, type: String })
    @ApiQuery({ name: 'search', required: false, type: String })
    @ApiQuery({ name: 'sort', required: false, type: String })
    async getTemplates(
        @Query('page') page = 1,
        @Query('pageSize') pageSize = 12,
        @Query('category') category?: string,
        @Query('search') search?: string,
        @Query('sort') sort = '-updateTime'
    ) {
        try {
            const query: any = {};

            if (category && category !== 'all') {
                query.category = category;
            }

            if (search) {
                query.$or = [
                    { name: { $regex: search, $options: 'i' } },
                    { description: { $regex: search, $options: 'i' } }
                ];
            }

            const sortOptions: { [key: string]: SortOrder } = {};
            if (sort) {
                const [field, order] = sort.startsWith('-')
                    ? [sort.slice(1), -1 as SortOrder]
                    : [sort, 1 as SortOrder];
                const fieldMap = {
                    createdAt: 'createTime',
                    updatedAt: 'updateTime'
                };
                sortOptions[fieldMap[field] || field] = order;
            }

            this.logger.debug('Query:', query);
            this.logger.debug('Sort:', sortOptions);

            return await this.workflowService.getTemplates(
                query,
                Number(page),
                Number(pageSize),
                sortOptions
            );
        } catch (error) {
            this.logger.error('Failed to get templates:', error);
            throw error;
        }
    }

    @Post()
    @UseGuards(JwtAuthGuard, RolesGuard)
    @Roles('admin')
    async createTemplate(@Body() template: Partial<WorkflowTemplate>) {
        return this.workflowService.createTemplate(template);
    }

    @Put(':id')
    @UseGuards(JwtAuthGuard, RolesGuard)
    @Roles('admin')
    async updateTemplate(
        @Param('id') id: string,
        @Body() template: Partial<WorkflowTemplate>
    ) {
        return this.workflowService.updateTemplate(id, template);
    }

    @Delete(':id')
    @UseGuards(JwtAuthGuard, RolesGuard)
    @Roles('admin')
    async deleteTemplate(@Param('id') id: string) {
        return this.workflowService.deleteTemplate(id);
    }

    @Get(':id')
    async getTemplate(@Param('id') id: string) {
        return this.workflowService.getTemplate(id);
    }

    @Post(':id/stats/:type')
    async updateStats(
        @Param('id') id: string,
        @Param('type') type: 'uses' | 'likes' | 'views'
    ) {
        await this.workflowService.updateStats(id, type);
        return { success: true };
    }
} 